package tjs.study.notes.dotest.proxy.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import tjs.study.notes.dotest.proxy.bytebuddy.service.Source;
import tjs.study.notes.dotest.proxy.bytebuddy.service.Target;

/**
 * Created by Nicky.Tang on 2021/10/8 4:41 下午
 *
 * @since 02.12.10
 */
public class DoTestOfByteBuddy {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        new ByteBuddy()
                .subclass(Source.class)
                //将sorce.hellowWorld()替换成Target.hellowWorld()
                .method(ElementMatchers.named("hellowWorld")).intercept(MethodDelegation.to(Target.class))
                .make()
                .load(DoTestOfByteBuddy.class.getClassLoader()).getLoaded()
                .newInstance()
                .hellowWorld();
//        //分开写
//        DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
//                .subclass(Source.class)
//                .method(ElementMatchers.named("hellowWorld")).intercept(MethodDelegation.to(Target.class))
//                .make();
//        // 加载类
//        Class<?> clazz = dynamicType.load(DoTestOfByteBody.class.getClassLoader())
//                .getLoaded();
//        // 反射调用
//        clazz.getMethod("hellowWorld").invoke(clazz.newInstance());

    }


//    静态内部类会报错
//    static class Source {
//        public void hellowWorld() {
//            System.out.println("say nothing!");
//        }
//    }
//
//    static class Target {
//        public static void hellowWorld() {
//            System.out.println("say hellowWorld!");
//        }
//    }
}
